package com.fourforfo.fourmall.ware.listener;

import com.alibaba.fastjson.TypeReference;
import com.fourforfo.common.to.mq.OrderTO;
import com.fourforfo.common.to.mq.StockDetailTO;
import com.fourforfo.common.to.mq.StockLockedTO;
import com.fourforfo.common.utils.R;
import com.fourforfo.fourmall.ware.dao.WareSkuDao;
import com.fourforfo.fourmall.ware.entity.WareOrderTaskDetailEntity;
import com.fourforfo.fourmall.ware.entity.WareOrderTaskEntity;
import com.fourforfo.fourmall.ware.entity.WareSkuEntity;
import com.fourforfo.fourmall.ware.feign.OrderFeignService;
import com.fourforfo.fourmall.ware.service.WareOrderTaskDetailService;
import com.fourforfo.fourmall.ware.service.WareOrderTaskService;
import com.fourforfo.fourmall.ware.service.WareSkuService;
import com.fourforfo.fourmall.ware.vo.OrderVO;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @program: xxl-sso-core
 * @description: 监听库存解锁消息
 * @author: fourforfo
 * @email: fourforfo@gmail.com
 * @create: 2022-09-11 15:45
 **/
@Slf4j
@Component
@RabbitListener(queues = "stock.release.queue")
public class StockReleaseListener {


    @Autowired
    OrderFeignService orderFeignService;

    @Autowired
    WareOrderTaskService wareOrderTaskService;

    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    WareSkuService wareSkuService;

    @Autowired
    WareSkuDao wareSkuDao;


    /**
     * 订单自动关闭发来的消息
     * @param orderTO
     * @param message
     * @param channel
     */
    @RabbitHandler
    public void handleOrderCloseRelease(OrderTO orderTO, Message message, Channel channel) throws Exception{
        try {

            log.info("订单关闭后解锁库存");
            wareSkuService.unlockStock(orderTO);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
        }

    }

    /**
     * 订单服务远程发送请求锁定库存结果
     *  情形一：1.用户订单30分钟未支付，订单过期，库存自动解锁
     *        2.或者订单锁定成功，接下来业务调用失败，导致订单回滚
     *  情形二：用户生成订单失败，
     *        借助消息队列发送回滚消息给库存服务，
     *        库存服务监听消息进行回滚，
     *        实现分布式事务回滚功能，达到最终一个性。
     * @param stockLockedTO
     * @param message
     * @param channel
     */
    @Transactional
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTO stockLockedTO, Message message, Channel channel) throws IOException {
        try{
            log.info("延迟队列过期后执行库存解锁！");
            Long taskId = stockLockedTO.getTaskId();
            List<StockDetailTO> details = stockLockedTO.getDetails();

            if(stockLockedTO==null||taskId==null||details==null||details.size()==0){
                log.error("监听的订单id为空，排查发送消息的服务是否有误！");
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
                return;
            }
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(taskId);
            String orderSn = taskEntity.getOrderSn();
            R r = orderFeignService.getOrderStatus(orderSn);
            if(r.getCode()!=0){
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
                return;
            }

            OrderVO orderVO = r.getData(new TypeReference<OrderVO>() {
            });

            /**
             * 没有该订单：解锁（属于订单锁定成功，但是接下来订单服务的业务调用失败，导致需要订单回滚）
             * 有该订单：订单状态为已取消：解锁库存（即订单30分钟后未支付自动取消）
             *          订单状态不是已取循：不能解锁（由订单支付成功时将订单状态改为已支付，然后将更新库存数量为：库存数量-锁定的库存数量，且将该订单的库存锁定清零）*/

            if(orderVO==null||orderVO.getStatus()==4){//订单被取消或者生成订单时服务发生异常
                //解锁库存
                unLockStock(details,taskId);

            }else{//订单没被取消

            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
        }

    }


    /**
     * 解锁库存方法
     * @param details
     */
    private void unLockStock(List<StockDetailTO> details,Long taskId){
        System.out.println("unLockStock执行："+details);

        List<WareOrderTaskDetailEntity> detailEntities = details.stream().map(stockDetailTO -> {
            WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity();
            detailEntity.setId(stockDetailTO.getId());
            detailEntity.setLockStatus(2);//设为已解锁状态
            return detailEntity;
        }).collect(Collectors.toList());
        /**
         * 更新库存
         */
        wareSkuDao.unLockStocks(detailEntities);

        /**
         * 更新订单任务项状态
         */
        wareOrderTaskDetailService.updateBatchById(detailEntities);


        /**
         * 更新任务状态
         */
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setId(taskId);
        taskEntity.setTaskStatus(2);//设任务状态为已解锁
        wareOrderTaskService.updateById(taskEntity);
    }


}
